﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WISD.CarFriend.BLL.Web;
using System.Data;
using System.Web.UI.HtmlControls;

namespace WISD.CarFriend.Web.Admin
{
    public partial class Login : System.Web.UI.Page
    {
        #region 字段
        UserManageModule m_UserManageModule = new UserManageModule();
        static string[] m_UserDirs = new string[] { "Config", "Home", "pub", "Temp" };
        #endregion


        #region 事件
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string str = Core.ServerImpl.Instance.GetUserName(Context);
            }
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ibtnLogin_Click(object sender, ImageClickEventArgs e)
        {
            this.LoginAdmin();
        }
        #endregion


        #region 方法
        /// <summary>
        /// 登录
        /// </summary>
        private void LoginAdmin()
        {
            try
            {
                string userName = this.txtUserName.Text.Trim();
                string userPassword = this.txtUserPassword.Text.Trim();
                if (userName.Equals("") || userPassword.Equals(""))
                {
                    this.lblMessage.Text = "请输入登录用户名或密码";
                }
                else
                {
                    if (Session["CountOfLogin"] == null)
                    {
                        Session["CountOfLogin"] = 1;
                    }
                    else
                    {
                        Session["CountOfLogin"] = Convert.ToInt32(Session["CountOfLogin"]) + 1;
                    }

                    //判断登录
                    if (Session["CountOfLogin"] != null && Convert.ToInt32(Session["CountOfLogin"]) > 3)
                    {
                        this.lblMessage.Text = "登录错误超过3次，请关闭浏览器重新登录。";
                    }
                    else if (this.m_UserManageModule.CheckLoign(userName, userPassword))
                    {
                        DataTable dt = this.m_UserManageModule.GetUsers("  a.UserCode='" + userName + "' ").Tables[0];
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            Session["UserID"] = dt.Rows[0]["UserID"].ToString();
                            Session["UserCode"] = dt.Rows[0]["UserCode"].ToString();
                            Session["UserName"] = dt.Rows[0]["UserName"].ToString();
                            Session["UserType"] = dt.Rows[0]["UserType"].ToString();
                            Session["UserPermission"] = dt.Rows[0]["UserPermission"].ToString();
                            Session["UserRole"] = dt.Rows[0]["UserRole"].ToString();
                        }

                        //设置超时时间
                        Session.Timeout = 45;
                        Session["CountOfLogin"] = null;

                        LoginChat(userName, userPassword);
                    }
                    else
                    {
                        this.lblMessage.Text = "您输入的用户名或密码不正确";
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblMessage.Text = "登录出错，请联系管理员。";
            }
        }


        /// <summary>
        /// 登录聊天
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPWD"></param>
        private void LoginChat(string userName, string userPWD)
        {
            try
            {
                String sessionId = Guid.NewGuid().ToString().ToUpper();

                if (Core.AccountImpl.Instance.Validate(userName, userPWD))
                {
                    foreach (string dir in m_UserDirs)
                    {
                        String path = String.Format("/{0}/{1}", "admin", dir);
                        if (!Core.IO.Directory.Exists(path)) Core.IO.Directory.CreateDirectory(path);
                    }

                    (FindControl("status") as HtmlInputHidden).Value = "login";
                    (FindControl("data") as HtmlInputHidden).Value = Core.Utility.RenderHashJson(
                        "UserInfo", Core.AccountImpl.Instance.GetUserInfo(userName).DetailsJson
                    );

                    Core.ServerImpl.Instance.Login(sessionId, Context, userName, null);
                }
                else
                {
                    throw new Exception("用户不存在或密码错误！");
                }
            }
            catch (Exception)
            { }
            finally
            {
                Response.Redirect("Index.aspx");
            }
        }
        #endregion
    }
}